<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="为什么进行二进制重排  当用户点击 App 启动的时候，系统会创建进程并为进程申请一块虚拟内存，虚拟内存和物理内存是需要映射的。当进程需要访问的一块虚拟内存页还没有映射对应的物理内存页时，就会触发一次缺页中断 Page In。这个过程中会发生 I&#x2F;O 操作，将磁盘中的数据读入到物理内存页中。如果读入的是 Text 段的页，还需要解密，并且系统还会对解密后的页进行签名验证。所以，如果在启动过程中频繁">
<meta property="og:type" content="article">
<meta property="og:title" content="二进制重排">
<meta property="og:url" content="http://example.com/2023/01/16/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/index.html">
<meta property="og:site_name" content="Shi">
<meta property="og:description" content="为什么进行二进制重排  当用户点击 App 启动的时候，系统会创建进程并为进程申请一块虚拟内存，虚拟内存和物理内存是需要映射的。当进程需要访问的一块虚拟内存页还没有映射对应的物理内存页时，就会触发一次缺页中断 Page In。这个过程中会发生 I&#x2F;O 操作，将磁盘中的数据读入到物理内存页中。如果读入的是 Text 段的页，还需要解密，并且系统还会对解密后的页进行签名验证。所以，如果在启动过程中频繁">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://raw.githubusercontent.com/shijianmei/blog_Images/main/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/%E7%BC%BA%E9%A1%B5%E4%B8%AD%E6%96%AD%E5%89%8D.png">
<meta property="og:image" content="https://raw.githubusercontent.com/shijianmei/blog_Images/main/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/launchPage.png">
<meta property="og:image" content="https://raw.githubusercontent.com/shijianmei/blog_Images/main/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/linkMap.png">
<meta property="og:image" content="https://raw.githubusercontent.com/shijianmei/blog_Images/main/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/%E7%BC%BA%E9%A1%B5%E4%B8%AD%E6%96%AD%E5%89%8D.png">
<meta property="og:image" content="https://raw.githubusercontent.com/shijianmei/blog_Images/main/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/%E4%BC%98%E5%8C%96%E5%90%8E%E7%BC%BA%E9%A1%B5%E4%B8%AD%E6%96%AD%E5%88%86%E6%9E%90.png">
<meta property="article:published_time" content="2023-01-16T08:15:40.000Z">
<meta property="article:modified_time" content="2023-04-25T10:47:39.966Z">
<meta property="article:author" content="Shi">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://raw.githubusercontent.com/shijianmei/blog_Images/main/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/%E7%BC%BA%E9%A1%B5%E4%B8%AD%E6%96%AD%E5%89%8D.png">

<link rel="canonical" href="http://example.com/2023/01/16/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>二进制重排 | Shi</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Shi</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2023/01/16/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Shi">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Shi">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          二进制重排
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2023-01-16 16:15:40" itemprop="dateCreated datePublished" datetime="2023-01-16T16:15:40+08:00">2023-01-16</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/source/categories/iOS%E4%BC%98%E5%8C%96/" itemprop="url" rel="index"><span itemprop="name">iOS优化</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="为什么进行二进制重排"><a href="#为什么进行二进制重排" class="headerlink" title="为什么进行二进制重排"></a>为什么进行二进制重排</h1><p>  当用户点击 App 启动的时候，系统会创建进程并为进程申请一块虚拟内存，虚拟内存和物理内存是需要映射的。当进程需要访问的一块虚拟内存页还没有映射对应的物理内存页时，就会触发一次缺页中断 Page In。这个过程中会发生 I/O 操作，将磁盘中的数据读入到物理内存页中。如果读入的是 Text 段的页，还需要解密，并且系统还会对解密后的页进行签名验证。所以，如果在启动过程中频繁的发生 Page In 的话，Page In 引起的 I/O 操作以及解密验证操作等的耗时也是影响很大的。需要注意的是，iOS13 及以后苹果对这个过程进行了优化，Page In 的时候不再需要解密了。</p>
<p>  Page In 的具体情况我们可以通过 Instruments 中的 System Trace 工具来分析，其中找到 Main Thread 进程，再选择 Summary:Virtual Memory 选项，下面看到的 File Backed Page In 就是对应的缺页中断数据了，如下图所示：</p>
<p><img src="https://raw.githubusercontent.com/shijianmei/blog_Images/main/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/%E7%BC%BA%E9%A1%B5%E4%B8%AD%E6%96%AD%E5%89%8D.png"></p>
<p>在启动过程中过多的 Page In 会产生过多的 I/O 操作以及解密验证操作，这些操作的耗时影响也会比较大。针对 Page In 的影响，我们可以通过二进制重排来减少这个过程的耗时。我们知道进程在访问虚拟内存的时候是以页为单位的，而启动过程中的两个方法如果在不同的页，系统就会进行两次缺页中断 Page In 操作来加载这两个页。而如果启动链路上的方法分散在不同的页的话，整个启动的过程就会产生非常多的 Page In 操作。为了能减少系统因缺页中断产生的 Page In 操作，我们需要做的就是把启动链路上所有用到的方法都排在连续的页上，这样系统在加载符号的时候就可以减少相应的内存页数量的访问，从而减少整个启动过程的耗时，如下图所示：<br><img src="https://raw.githubusercontent.com/shijianmei/blog_Images/main/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/launchPage.png"> </p>
<p>  要实现符号的重排，一是需要我们收集整个启动链路上的方法和函数等符号，二是需要生成对应的 order 文件来配置 ld 中的 Order File 属性。当工程在编译的时候，Xcode 会读取这个 order 文件，在链接过程中会根据这个文件中的符号顺序来生成对应的 MachO。一般业界中收集符号的方案有两种：</p>
<ul>
<li> Hook objc_msgSend，只能拿到 OC 以及 swift @objc dynamic 的符号； </li>
<li> Clang 插桩，能完美拿到 OC、C/C++、Swift、Block 的符号；<br>故这里采用Clang插桩方式来搜集符号,具体实现如下:</li>
</ul>
<h1 id="具体实现"><a href="#具体实现" class="headerlink" title="具体实现"></a>具体实现</h1><h2 id="1-添加-Build-Setting-设置"><a href="#1-添加-Build-Setting-设置" class="headerlink" title="1. 添加 Build Setting 设置"></a>1. 添加 Build Setting 设置</h2><p>Target -&gt; Build Setting -&gt; Custom Complier Flags -&gt; Other C Flags 添加</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">-fsanitize-coverage=func,trace-pc-guard</span><br></pre></td></tr></table></figure>
<p>Other Swift Flags 添加</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">-sanitize-coverage=func -sanitize=undefined</span><br></pre></td></tr></table></figure>
<p> 项目如果是组件化的话,需要分别对主工程,及各组件进行设置,可以通过脚本在podfile设置</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"># 二进制重排设置</span><br><span class="line">  installer.pods_project.targets.each do |target|</span><br><span class="line">    target.build_configurations.each do |config|</span><br><span class="line">      if config.name == &#x27;Debug&#x27;</span><br><span class="line">        config.build_settings[&#x27;OTHER_CFLAGS&#x27;] ||= &#x27;$(inherited)&#x27;</span><br><span class="line">        config.build_settings[&#x27;OTHER_CFLAGS&#x27;] &lt;&lt; &#x27; &#x27;</span><br><span class="line">        config.build_settings[&#x27;OTHER_CFLAGS&#x27;] &lt;&lt; &#x27;-fsanitize-coverage=func,trace-pc-guard&#x27;</span><br><span class="line">      end</span><br><span class="line">    end</span><br><span class="line">  end</span><br><span class="line"></span><br><span class="line"># 主工程二进制重排设置</span><br><span class="line">  app_project.native_targets.each do |target|</span><br><span class="line">    if target.name == &#x27;AiWayFashionCar&#x27;</span><br><span class="line">      target.build_configurations.each do |config|</span><br><span class="line">        if config.name == &#x27;Debug&#x27;</span><br><span class="line">          config.build_settings[&#x27;OTHER_CFLAGS&#x27;] ||= &#x27;$(inherited)&#x27;</span><br><span class="line">          config.build_settings[&#x27;OTHER_CFLAGS&#x27;] &lt;&lt; &#x27; &#x27;</span><br><span class="line">          config.build_settings[&#x27;OTHER_CFLAGS&#x27;] &lt;&lt; &#x27;-fsanitize-coverage=func,trace-pc-guard&#x27;</span><br><span class="line">        end</span><br><span class="line">      end</span><br><span class="line">    end</span><br><span class="line">  end</span><br></pre></td></tr></table></figure>
<h2 id="2-添加代码"><a href="#2-添加代码" class="headerlink" title="2. 添加代码"></a>2. 添加代码</h2><p> 在启动队列添加代码</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">if</span> DEBUG</span></span><br><span class="line">    AppOrderFiles(^(<span class="built_in">NSString</span> * _Nonnull orderFilePath) &#123;</span><br><span class="line">        <span class="built_in">NSLog</span>(<span class="string">@&quot;orderFilePath:%@&quot;</span>,orderFilePath);</span><br><span class="line">    &#125;);</span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br></pre></td></tr></table></figure>
<p>添加类</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#import <span class="string">&lt;Foundation/Foundation.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="built_in">NS_ASSUME_NONNULL_BEGIN</span></span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">AWLaunchManager</span> : <span class="title">NSObject</span></span></span><br><span class="line"><span class="keyword">extern</span> <span class="type">void</span> AppOrderFiles(<span class="type">void</span>(^completion)(<span class="built_in">NSString</span> *orderFilePath));</span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"><span class="built_in">NS_ASSUME_NONNULL_END</span></span><br></pre></td></tr></table></figure>

<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#import <span class="string">&quot;AWLaunchAnalysisLog.h&quot;</span></span></span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">AWLaunchManager</span></span></span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">if</span> DEBUG</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#import <span class="string">&lt;dlfcn.h&gt;</span></span></span><br><span class="line"><span class="meta">#import <span class="string">&lt;libkern/OSAtomicQueue.h&gt;</span></span></span><br><span class="line"><span class="meta">#import <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 队列头的数据结构。</span></span><br><span class="line"><span class="keyword">static</span> OSQueueHead queue = OS_ATOMIC_QUEUE_INIT;</span><br><span class="line"><span class="keyword">static</span> <span class="type">BOOL</span> collectFinished = <span class="literal">NO</span>;</span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">struct</span> &#123;</span><br><span class="line">    <span class="type">void</span> *pc;</span><br><span class="line">    <span class="type">void</span> *next;</span><br><span class="line">&#125; PCNode;</span><br><span class="line"></span><br><span class="line"><span class="comment">// The guards are [start, stop).</span></span><br><span class="line"><span class="comment">// This function will be called at least once per DSO and may be called</span></span><br><span class="line"><span class="comment">// more than once with the same values of start/stop.</span></span><br><span class="line"><span class="type">void</span> __sanitizer_cov_trace_pc_guard_init(uint32_t *start,</span><br><span class="line">                                         uint32_t *stop) &#123;</span><br><span class="line">    <span class="keyword">static</span> uint32_t Counter;  <span class="comment">// Counter for the guards.</span></span><br><span class="line">    <span class="keyword">if</span> (start == stop || *start) <span class="keyword">return</span>;  <span class="comment">// Initialize only once.</span></span><br><span class="line">    printf(<span class="string">&quot;INIT: %p %p\n&quot;</span>, start, stop);</span><br><span class="line">    <span class="keyword">for</span> (uint32_t *x = start; x &lt; stop; x++)&#123;</span><br><span class="line">        *x = ++Counter;  <span class="comment">// Guards should start from 1.</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// This callback is inserted by the compiler on every edge in the</span></span><br><span class="line"><span class="comment">// control flow (some optimizations apply).</span></span><br><span class="line"><span class="comment">// Typically, the compiler will emit the code like this:</span></span><br><span class="line"><span class="comment">//    if(*guard)</span></span><br><span class="line"><span class="comment">//      __sanitizer_cov_trace_pc_guard(guard);</span></span><br><span class="line"><span class="comment">// But for large functions it will emit a simple call:</span></span><br><span class="line"><span class="comment">//    __sanitizer_cov_trace_pc_guard(guard);</span></span><br><span class="line"><span class="comment">// 该回调由编译器插入到</span></span><br><span class="line"><span class="comment">// 控制流（适用一些优化）</span></span><br><span class="line"><span class="comment">// 通常，编译器将发出如下代码：</span></span><br><span class="line"><span class="comment">//    if(*guard)</span></span><br><span class="line"><span class="comment">//      __sanitizer_cov_trace_pc_guard(guard);</span></span><br><span class="line"><span class="comment">// But for large functions it will emit a simple call:</span></span><br><span class="line"><span class="comment">//    __sanitizer_cov_trace_pc_guard(guard);</span></span><br><span class="line"><span class="type">void</span> __sanitizer_cov_trace_pc_guard(uint32_t *guard) &#123;</span><br><span class="line">    <span class="keyword">if</span> (collectFinished || !*guard) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// If you set *guard to 0 this code will not be called again for this edge.</span></span><br><span class="line">    <span class="comment">// Now you can get the PC and do whatever you want:</span></span><br><span class="line">    <span class="comment">//   store it somewhere or symbolize it and print right away.</span></span><br><span class="line">    <span class="comment">// The values of `*guard` are as you set them in</span></span><br><span class="line">    <span class="comment">// __sanitizer_cov_trace_pc_guard_init and so you can make them consecutive</span></span><br><span class="line">    <span class="comment">// and use them to dereference an array or a bit vector.</span></span><br><span class="line">    *guard = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">// __builtin_return_address(0)的含义是，得到当前函数返回地址，即此函数被别的函数调用，然后此函数执行完毕后，返回，所谓返回地址就是那时候的地址</span></span><br><span class="line">    <span class="type">void</span> *PC = __builtin_return_address(<span class="number">0</span>);</span><br><span class="line">    PCNode *node = malloc(<span class="keyword">sizeof</span>(PCNode));</span><br><span class="line">    *node = (PCNode)&#123;PC, <span class="literal">NULL</span>&#125;;</span><br><span class="line">    OSAtomicEnqueue(&amp;queue, node, offsetof(PCNode, next));</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">extern</span> <span class="type">void</span> AppOrderFiles(<span class="type">void</span>(^completion)(<span class="built_in">NSString</span> *orderFilePath)) &#123;</span><br><span class="line"><span class="meta">#<span class="keyword">if</span> DEBUG</span></span><br><span class="line">    collectFinished = <span class="literal">YES</span>;</span><br><span class="line">    __sync_synchronize();</span><br><span class="line">    <span class="built_in">NSString</span> *functionExclude = [<span class="built_in">NSString</span> stringWithFormat:<span class="string">@&quot;_%s&quot;</span>, __FUNCTION__];</span><br><span class="line">    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<span class="number">0.01</span> * <span class="built_in">NSEC_PER_SEC</span>)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="number">0</span>), ^&#123;</span><br><span class="line">        <span class="built_in">NSMutableArray</span> &lt;<span class="built_in">NSString</span> *&gt; *functions = [<span class="built_in">NSMutableArray</span> array];</span><br><span class="line">        <span class="keyword">while</span> (<span class="literal">YES</span>) &#123;</span><br><span class="line">            PCNode *node = OSAtomicDequeue(&amp;queue, offsetof(PCNode, next));</span><br><span class="line">            <span class="keyword">if</span> (node == <span class="literal">NULL</span>) &#123;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            Dl_info info = &#123;<span class="number">0</span>&#125;;</span><br><span class="line">            dladdr(node-&gt;pc, &amp;info);</span><br><span class="line">            <span class="keyword">if</span> (info.dli_sname) &#123;</span><br><span class="line">                <span class="built_in">NSString</span> *name = @(info.dli_sname);</span><br><span class="line">                <span class="type">BOOL</span> isObjc = [name hasPrefix:<span class="string">@&quot;+[&quot;</span>] || [name hasPrefix:<span class="string">@&quot;-[&quot;</span>];</span><br><span class="line">                <span class="built_in">NSString</span> *symbolName = isObjc ? name : [<span class="string">@&quot;_&quot;</span> stringByAppendingString:name];</span><br><span class="line">                [functions addObject:symbolName];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (functions.count == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (completion) &#123;</span><br><span class="line">                completion(<span class="literal">nil</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">NSMutableArray</span>&lt;<span class="built_in">NSString</span> *&gt; *calls = [<span class="built_in">NSMutableArray</span> arrayWithCapacity:functions.count];</span><br><span class="line">        <span class="built_in">NSEnumerator</span> *enumerator = [functions reverseObjectEnumerator];</span><br><span class="line">        <span class="built_in">NSString</span> *obj;</span><br><span class="line">        <span class="keyword">while</span> (obj = [enumerator nextObject]) &#123;</span><br><span class="line">            <span class="keyword">if</span> (![calls containsObject:obj]) &#123;</span><br><span class="line">                [calls addObject:obj];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        [calls removeObject:functionExclude];</span><br><span class="line">        <span class="built_in">NSString</span> *result = [calls componentsJoinedByString:<span class="string">@&quot;\n&quot;</span>];</span><br><span class="line"><span class="comment">//        NSLog(@&quot;二进制重排MethodOrder地址:\n%@&quot;, result);</span></span><br><span class="line"><span class="comment">//        printf(&quot;%s&quot;,[result cStringUsingEncoding:NSUTF8StringEncoding]);</span></span><br><span class="line">        </span><br><span class="line">        <span class="built_in">NSString</span> *filePath = [<span class="built_in">NSTemporaryDirectory</span>() stringByAppendingPathComponent:<span class="string">@&quot;app.order&quot;</span>];</span><br><span class="line">        <span class="built_in">NSData</span> *fileContents = [result dataUsingEncoding:<span class="built_in">NSUTF8StringEncoding</span>];</span><br><span class="line">        <span class="type">BOOL</span> success = [[<span class="built_in">NSFileManager</span> defaultManager] createFileAtPath:filePath</span><br><span class="line">                                                               contents:fileContents</span><br><span class="line">                                                             attributes:<span class="literal">nil</span>];</span><br><span class="line">        <span class="keyword">if</span> (success ) &#123;</span><br><span class="line">            <span class="keyword">if</span> (completion) &#123;</span><br><span class="line">                completion(filePath);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-取出-order-file"><a href="#3-取出-order-file" class="headerlink" title="3. 取出 order file"></a>3. 取出 order file</h2><ul>
<li>在debug模式下编译代码后会在控制台打印 <code>lbfunc.order</code> 的路径</li>
<li>在控制台搜 “orderFilePath”</li>
<li><code>Finder</code> 前往路径取出 <code>order file</code></li>
</ul>
<h2 id="4-设置-order-file"><a href="#4-设置-order-file" class="headerlink" title="4. 设置 order file"></a>4. 设置 order file</h2><ul>
<li>把 <code>lbfunc.order</code> 的路径放到主工程根目录</li>
<li><code>Target -&gt; Build Setting -&gt; Linking -&gt; Order File</code> 设置路径</li>
</ul>
<h1 id="查看自己工程的符号顺序"><a href="#查看自己工程的符号顺序" class="headerlink" title="查看自己工程的符号顺序"></a>查看自己工程的符号顺序</h1><p>重排前后我们需要查看自己的符号顺序有没有修改成功 , 这时候就用到了 Link Map .</p>
<p>Link Map 是编译期间产生的产物 ,  ( ld 的读取二进制文件顺序默认是按照 Compile Sources - GUI 里的顺序 ) ,  它记录了二进制文件的布局 . 通过设置 Write Link Map File 来设置输出与否 , 默认是 no ,在编译完成后通过验证 LinkMap 文件中 #Symbols: 部分符号顺序是否和 order 文件中的符号顺序一致来确定是否配置成功<br><img src="https://raw.githubusercontent.com/shijianmei/blog_Images/main/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/linkMap.png"></p>
<h1 id="效果对比"><a href="#效果对比" class="headerlink" title="效果对比"></a>效果对比</h1><p>优化前<br><img src="https://raw.githubusercontent.com/shijianmei/blog_Images/main/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/%E7%BC%BA%E9%A1%B5%E4%B8%AD%E6%96%AD%E5%89%8D.png"><br>优化后<br><img src="https://raw.githubusercontent.com/shijianmei/blog_Images/main/%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92/%E4%BC%98%E5%8C%96%E5%90%8E%E7%BC%BA%E9%A1%B5%E4%B8%AD%E6%96%AD%E5%88%86%E6%9E%90.png"></p>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2022/08/20/%E4%B8%80%E6%AC%A1%E5%8D%A1%E9%A1%BF%E4%BC%98%E5%8C%96/" rel="prev" title="一次卡顿优化">
      <i class="fa fa-chevron-left"></i> 一次卡顿优化
    </a></div>
      <div class="post-nav-item">
    <a href="/2023/01/21/%E5%90%AF%E5%8A%A8%E4%BC%98%E5%8C%96/" rel="next" title="启动优化">
      启动优化 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%9B%E8%A1%8C%E4%BA%8C%E8%BF%9B%E5%88%B6%E9%87%8D%E6%8E%92"><span class="nav-number">1.</span> <span class="nav-text">为什么进行二进制重排</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%85%B7%E4%BD%93%E5%AE%9E%E7%8E%B0"><span class="nav-number">2.</span> <span class="nav-text">具体实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E6%B7%BB%E5%8A%A0-Build-Setting-%E8%AE%BE%E7%BD%AE"><span class="nav-number">2.1.</span> <span class="nav-text">1. 添加 Build Setting 设置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E6%B7%BB%E5%8A%A0%E4%BB%A3%E7%A0%81"><span class="nav-number">2.2.</span> <span class="nav-text">2. 添加代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E5%8F%96%E5%87%BA-order-file"><span class="nav-number">2.3.</span> <span class="nav-text">3. 取出 order file</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E8%AE%BE%E7%BD%AE-order-file"><span class="nav-number">2.4.</span> <span class="nav-text">4. 设置 order file</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%9F%A5%E7%9C%8B%E8%87%AA%E5%B7%B1%E5%B7%A5%E7%A8%8B%E7%9A%84%E7%AC%A6%E5%8F%B7%E9%A1%BA%E5%BA%8F"><span class="nav-number">3.</span> <span class="nav-text">查看自己工程的符号顺序</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%95%88%E6%9E%9C%E5%AF%B9%E6%AF%94"><span class="nav-number">4.</span> <span class="nav-text">效果对比</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Shi</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">9</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/shijianmei" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;shijianmei" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        <!--

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Shi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>
-->

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
